<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-select
          v-model="timeRange"
          @change="handleTimeChange"
          style="margin-bottom: 15px"
        >
          <el-option label="近7日" value="7days"></el-option>
          <el-option label="近1月" value="30days"></el-option>
          <el-option label="近1年" value="365days"></el-option>
        </el-select>
        <div id="main" style="width: 100%; height: 400px"></div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { selectRecruitsByVisitCount } from "@/api/auditRecord";

export default {
  data() {
    return {
      myChart: null,
      timeRange: "7days",
    };
  },
  mounted() {
    this.initChart();
    this.getChartHandler();
  },
  methods: {
    //初始化
    initChart() {
      const chartDom = document.getElementById("main");
      this.myChart = echarts.init(chartDom);

      const option = {
        xAxis: {
          type: "category",
          data: [],
          axisLabel: {
            // 防止名称过长显示不全
            rotate: 30,
            interval: 0,
          },
        },
        yAxis: {
          type: "value",
          name: "浏览量",
        },
        series: [
          {
            name: "浏览量",
            data: [],
            type: "bar",
          },
        ],
        tooltip: {
          trigger: "item",
          formatter: (params) => {
            // 从数据中提取公司名、职位名、浏览量
            const { recruitName, companyName, value } = params.data;
            return `
              职位：${recruitName}<br/>
              公司：${companyName}<br/>
              浏览量：${value}
            `;
          },
        },
        legend: {
          data: ["浏览量"],
        },
      };

      this.myChart.setOption(option);
    },

    //获取
    getChartHandler() {
      selectRecruitsByVisitCount(this.timeRange).then((response) => {
        if (response.code === 200) {
          // 获取x轴招聘信息职位名称
          const xAxisData = response.data.map((item) => item.recruitName);
          // 获取柱状图显示的公司名、职位名、浏览量
           const seriesData = response.data.map((item) => ({
              value: item.visitCount, 
              companyName: item.companyName, 
              recruitName: item.recruitName, 
            }));
          // 更新图表
          this.myChart.setOption({
            xAxis: {    
              data: xAxisData,
            },
            series: [
              {
                name: "浏览量",
                data: seriesData,
              },
            ],
          });
        }
      });
    },
    //切换时间范围查询
    handleTimeChange() {
      this.getChartHandler();
    },
  },
  // 窗口大小变化时重绘图表
  beforeDestroy() {
    if (this.myChart) {
      this.myChart.dispose();
    }
  },
};
</script>

<style>
#main {
  margin: 0 auto;
}
</style>
